using Microsoft.EntityFrameworkCore;
using UniversalAdminSystem.Domian.PermissionManagement.Aggregate;
using UniversalAdminSystem.Domian.PermissionManagement.IRepository;
using UniversalAdminSystem.Domian.PermissionManagement.ValueObjects;
using UniversalAdminSystem.Infrastructure.Persistence.DbContexts;

namespace UniversalAdminSystem.Infrastructure.Persistence.Repositories;

public class PermissionRepository : BaseRepository<Permission>, IPermissionRepository
{
    public PermissionRepository(UniversalAdminSystemDbContext dbContext) : base(dbContext)
    {
    }

    /// <summary>
    /// 批量持久化系统权限
    /// </summary>
    /// <param name="permissions"></param>
    /// <returns></returns>
    public async Task AddSystemPermissionsAsync(IEnumerable<Permission> perms)
    {
        if (perms == null) throw new ArgumentNullException(nameof(perms));
        var permList = perms.ToList();
        if (!permList.Any()) return;

        using var transaction = await _DbContext.Database.BeginTransactionAsync();
        try
        {
            // 获取所有已存在的权限代码
            var existingCodes = await _TDs
                .Select(p => p.Code.Value)
                .ToListAsync();

            Console.WriteLine($"数据库中已存在的权限代码数量: {existingCodes.Count}");
            
            // 过滤出新的权限
            var newPermissions = permList
                .Where(p => !existingCodes.Contains(p.Code.Value))
                .ToList();

            Console.WriteLine($"需要添加的新权限数量: {newPermissions.Count}");
            
            if (newPermissions.Count > 0)
            {
                await _TDs.AddRangeAsync(newPermissions);
                await _DbContext.SaveChangesAsync();
                Console.WriteLine($"成功添加 {newPermissions.Count} 个新权限");
            }
            else
            {
                Console.WriteLine("所有权限都已存在，跳过添加");
            }

            await transaction.CommitAsync();
        }
        catch (Exception ex)
        {
            await transaction.RollbackAsync();
            Console.WriteLine($"添加系统权限失败: {ex.Message}");
            throw;
        }
    }

    public async Task<Permission?> GetByCodeAsync(PermissionCode code)
    {
        if (code == null) throw new ArgumentNullException(nameof(code));
        
        // 使用隐式转换，让EF Core能够正确转换查询
        var permission = await _TDs.FirstOrDefaultAsync(p => p.Code == code);
        
        if (permission != null)
        {
            System.Console.WriteLine($"找到权限: {permission.Code}");
        }
        else
        {
            System.Console.WriteLine($"未找到权限代码: {code}");
        }
        
        return permission;
    }

    public async Task<bool> ExistsAsync(PermissionCode code)
    {
        if (code == null) throw new ArgumentNullException(nameof(code));
        return await _TDs.AnyAsync(p => p.Code == code);
    }

    public async Task<IEnumerable<Permission>> GetByIdsAsync(IEnumerable<Guid> ids)
    {
        if (ids == null) throw new ArgumentNullException(nameof(ids));
        return await _TDs.Where(p => ids.Contains(p.PermissionId)).ToListAsync();
    }

    public async Task<IEnumerable<Permission>> QueryAsync(string? name = null, string? resource = null, int? action = null, PermissionType? type = null)
    {
        var query = _TDs.AsQueryable();
        if (!string.IsNullOrWhiteSpace(name))
            query = query.Where(p => p.Name.Value.Contains(name));
        if (!string.IsNullOrWhiteSpace(resource))
            query = query.Where(p => p.Resource.Value == resource);
        if (action.HasValue)
            query = query.Where(p => (int)p.Action == action.Value);
        if (type.HasValue)
            query = query.Where(p => p.PermissionType == type.Value);
        return await query.ToListAsync();
    }
}

